//
//  HomePageController.swift
//  YiYaoHui
//
//  Created by 高永效 on 15/11/29.
//  Copyright © 2015年 TMPercy. All rights reserved.
//

import UIKit
import SDWebImage
import Alamofire

class HomePageController: UIViewController{
    
    let searchURL = "http://112.74.131.194:8080/MedicineProject/App/res/getAllSearch"
    
    @IBOutlet weak var searchBar: UISearchBar!
    var isSearch:Bool = false
    var arrSeach = [String]()
    var arrTitle = [String]()
    var isLogin:Bool!
    
    var meeting : Meeting!
    var meetingLogoURL: String!
    let introduceController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("introducationController") as! MeetingIndrotucationController
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        searchBar.delegate = self
    }
    
    override func viewWillAppear(animated: Bool) {
        tabBarController?.tabBar.hidden = false
        navigationController?.navigationBarHidden = true
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "lastestMeeting" {
        let latestMeetingController = segue.destinationViewController as! LastestMeetingController
        latestMeetingController.id = 1
        }
    }
    
    
}

extension HomePageController: UITableViewDataSource {
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        case 1:
            return 1
        default:
            return 1
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        switch indexPath.section {
        case 0:
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCellWithIdentifier("headerCell", forIndexPath: indexPath)
                return cell
            }
            else {
                let cell = tableView.dequeueReusableCellWithIdentifier("meetingCell", forIndexPath: indexPath) as! MeetingCell
                let latestMeetingURL = "http://112.74.131.194:8080/MedicineProject/App/res/getRecentMeeting"
                Alamofire.request(.POST, latestMeetingURL, parameters: ["size": 1], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (_, _, result) -> Void in
                    if let value = result.value {
                        if let Meetings = value["Meetings"] as? [Dictionary<String, AnyObject>] {
                            for item in Meetings {
                                let meeting = Meeting(meeting: item)
                                self.introduceController.meeting = meeting
                                cell.titleLabel.text = meeting.name
                                cell.timeLabel.text = meeting.commitDate
                                cell.holderLabel.text = meeting.content
                                
                                if meeting.logoURL  == "" {
                                    cell.meetingLogo.image = UIImage(named: "meeting")

                                } else {
                                    self.meetingLogoURL = "http://112.74.131.194:8080/MedicineProject" + meeting.logoURL
                                    cell.meetingLogo.sd_setImageWithURL(NSURL(string: self.meetingLogoURL),placeholderImage: UIImage(named: "meeting"))
                                }
                            }
                        }
                    }
                    else {
                        //MARK: something error
                    }
                }
                return cell
            }
        default:
            let cell = tableView.dequeueReusableCellWithIdentifier("optionCell", forIndexPath: indexPath) as! OptionCell
            if indexPath.section == 2 {
                cell.optionImageView.image = UIImage(named: "video")
                cell.optionLabel.text = "医药视频"
            }
            return cell
        }
    }
    
}

extension HomePageController: UITableViewDelegate {
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            switch indexPath.row {
            case 0:
                return 40
            default:
                return 97
            }
        }
        return 44
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                let  latestMeetingControlelr = self.storyboard?.instantiateViewControllerWithIdentifier("MeetingController") as! LastestMeetingController
                latestMeetingControlelr.id = 1
                self.navigationController?.pushViewController(latestMeetingControlelr, animated: true)
                break
            case 1: //最近会议接,请求size为1
                self.navigationController?.pushViewController(introduceController, animated: true)
                break
            default:
                break
            }
            break
        case 1:
            //个人收藏
            isLogin = NSUserDefaults.standardUserDefaults().boolForKey("loginState")
            
            if isLogin == true {
                let CollectionController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("collectionController")
                self.navigationController?.pushViewController(CollectionController, animated: true)
            } else {
                let alert = UIAlertController(title: "您尚未登陆", message: "无法查看收藏", preferredStyle: .Alert)
                let loginAction = UIAlertAction(title: "登陆", style: .Default) { (action:UIAlertAction) -> Void in
                    let LoginController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginController")
                    self.navigationController?.pushViewController(LoginController, animated: true)
                }
                let cancelAction = UIAlertAction(title: "取消", style: .Default) { (action:UIAlertAction) -> Void in
                    //弹出框按了“取消”，然后取消操作为空即可。
                }
                alert.addAction(loginAction)
                alert.addAction(cancelAction)
                presentViewController(alert, animated: true, completion: nil)
            }
            break
        case 2:
            let latestVideoController = self.storyboard?.instantiateViewControllerWithIdentifier("VideoController") as!LastestVideoController
            latestVideoController.id = 1
            self.navigationController?.pushViewController(latestVideoController, animated: true)
            break
        default:
            break
        }
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}

extension HomePageController : UISearchBarDelegate {
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        onSeach(searchText)
    }

    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        onSeach(searchBar.text!)
        searchBar.resignFirstResponder()
    }

    func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
        searchBar.resignFirstResponder()
        return true
    }

    func onSeach(str:String){
        isSearch = true
        //将arrSearch数组清空
        arrSeach = [String]()
        for title in arrTitle{
            let index = title.rangeOfString(str)
            if (index?.isEmpty != nil){
                self.arrSeach.append(title)
            }
        }
    }
}


